<template>
	<view class="main">
		<image src="../../static/login/bg.png" mode="" class="bg"></image>
		<view class="form">
			<image src="../../static/login/logo.png" mode="widthFix" class="logo"></image>
			<form class="form-box">
				<view class="uni-form-item">
					<image src="../../static/login/username.png" mode="" class="icon"></image>
					<input placeholder-style="color: #ccc;" name="username" class="uni-input" v-model="username"
						placeholder="请输入姓名" maxlength="-1" />
				</view>
				<view class="uni-form-item">
					<image src="../../static/login/password.png" mode="" class="icon"></image>
					<input placeholder-style="color: #ccc;" name="password" id="uni-input-password" class="uni-input"
						placeholder="请输入密码" :password="true" v-model="password" />
				</view>
				<button hover-class="btn-hover" :plain="true" class="btn btn-submit" @click="onFormSubmit">登录</button>
				<checkbox :checked="isCheckout" class="checkbox" @click="isCheckout = !isCheckout"><text class="checkbox-text">记住密码</text></checkbox>
			</form>
		</view>
	</view>
</template>

<script setup>
	import {
		reactive,
		ref
	} from "vue"
	import RequestURL from "../../util/request.js";
	import CryptoJS from "../../util/aes1.js";
	import {onShow} from '@dcloudio/uni-app'
	
	let locaInfo = uni.getStorageSync('$state');
	let hasPassword = uni.getStorageSync('checked');
	let username = ref("");
	let password = ref("");
	let isCheckout = ref(true)
	if (locaInfo) {
		username.value = locaInfo.account;
		if (hasPassword) {
			password.value = locaInfo.password
		}
	}
	let loginInfo = reactive({})

	let onFormSubmit = () => {
		var loginInfo = {
			account: trimStr(username.value),
			password: password.value
		};
		console.log(JSON.stringify(loginInfo));
		login(loginInfo, function(err) {
			if (err) {
				plus.nativeUI.toast(err);
				return;
			}
			getUser();
			toIndex();
		});
	}
	
	function login(loginInfo, callback) {
		callback = callback;
		loginInfo = loginInfo || {};
		loginInfo.account = loginInfo.account || '';
		loginInfo.password = loginInfo.password || '';
			
		var connection = plus.networkinfo.getCurrentType();
		
		if("1"==connection || "0"==connection){
				loginInfo.name = loginInfo.account;;
				loginInfo.dep = '';
				loginInfo.telphone = '';
				loginInfo.email = '';
				loginInfo.version = plus.runtime.version;
	//			return getTocket1(loginInfo, callback);
				return createState(loginInfo, callback);
		}else{
			
			validityUser(loginInfo, function(authed) {
			if(authed) {
				loginInfo.name = authed.name || '';
				loginInfo.dep = authed.dep || '';
				loginInfo.telphone = authed.telphone || '';
				loginInfo.email = authed.email || '';
				loginInfo.version = plus.runtime.version;
				return getTocket(loginInfo, callback);
			} else {
				return callback('用户名或密码错误');
			}
		});
		}
	}
	
	function getTocket(loginInfo, callback) {
		var _url = RequestURL.getRequestURL('getTocket');
		var userid = loginInfo.account;
		var version = loginInfo.version;
		var data = {
			userid: loginInfo.account,
			version: version
		};
		uni.request({
			url: _url,
			method: 'POST',
			timeout: 5000,
			dataType: 'json',
			data: data,
			header: {
				'Accept': '*/*',
				'X-Requested-With': 'XMLHttpRequest',
				'Content-Type': 'application/x-www-form-urlencoded'
			},
			success: (res) => {
				let data = res.data;
				if(data.return_code == "SUCCESS") {
					loginInfo.tocket = data.values;
					return createState(loginInfo, callback);
				} else {
					return callback(data.return_msg);
				}
			},
			fail: function(xhr, type, errorThrown) {
				uni.showToast({
					title: '获取tocket失败',
					icon: 'none',
					duration: 2000
				})
			}
		})
	}
	
	function validityUser(loginInfo, callback) {
		var _url = RequestURL.getRequestURL('login');
		var username = loginInfo.account;
		var password = encrypt(loginInfo.password);
		var flag = "new";
		var jsondata = {username:username,password:password,flag:flag};
		
		uni.request({
			url: _url,
			method: 'POST',
			timeout: 5000,
			dataType: 'json',
			data: jsondata,
			header: {
				'Accept': '*/*',
				'X-Requested-With': 'XMLHttpRequest',
				'Content-Type': 'application/x-www-form-urlencoded'
			},
			success: (res) => {
				let data = res.data;
				console.log(JSON.stringify(data))
				if(data.RES_CODE == '0') {
					var user = {
						account: data.USR_ID,
						name: data.USR_NAME,
						email: data.USR_EMAIL,
						password: password.value
					}
					callback(user);
				} else {
					uni.showToast({
						title: '登录失败！' + data.RES_INFO,
						icon: 'none',
						duration: 2000
					})
				}
			},
			fail: function() {
				//异常处理
				uni.showToast({
					title: '服务器异常链接失败',
					icon: 'none',
					duration: 2000
				})
			}
		});
	}
	
	function trimStr(str){return str.replace(/(^\s*)|(\s*$)/g,"");}


	function encrypt(data) {
		var key = CryptoJS.enc.Latin1.parse('zhouzhongyan123!');
		var iv = CryptoJS.enc.Latin1.parse('zhouzhongyan123!');
		return CryptoJS.AES.encrypt(data, key, {
			iv: iv,
			mode: CryptoJS.mode.CBC,
			padding: CryptoJS.pad.ZeroPadding
		}).toString();
	}

	function createState(loginInfo, callback) {
		var state = {};
		state.account = loginInfo.account;
		state.version = loginInfo.version;
		state.tocket = loginInfo.tocket;
		state.name = loginInfo.name || '';
		state.dep = loginInfo.dep || '';
		state.telphone = loginInfo.telphone || '';
		state.email = loginInfo.email || '';
		state.password = password.value;
		setState(state);
		uni.showToast({
			title: '登录成功',
			icon: 'none',
			duration: 2000
		})
		uni.setStorageSync('checked', isCheckout.value);
		uni.navigateTo({
			url: '/pages/list/list'
		})
	}

	function setState(state) {
		state = state || {};
		uni.setStorageSync('$state', state);
	}
	
	function loginOut() {
		var _url = RequestURL.getRequestURL('loginout');
		var user = uni.getStorageSync('$state');
		var userid = user.account;
		var jsondata = {
			"USR_ID": userid,
			"USR_PASSWORD": "",
			"ENV_DS_ID": "",
			"USR_LAN": "",
			"USR_EMAIL": "",
			"ENV_SERVICE_ID": "",
			"SEC_ENABLE": "",
			"SEC_SIGNTEXT": "",
			"SEC_TOKEN": ""
		};
		uni.request({
			url: _url,
			method: 'POST',
			timeout: 5000,
			dataType: 'json',
			data: jsondata,
			header: {
				'Accept': '*/*',
				'X-Requested-With': 'XMLHttpRequest',
				'Content-Type': 'application/x-www-form-urlencoded'
			},
		});
	}
	onShow(()=>{
		loginOut()
	})
</script>

<style lang="scss">
	.main {
		flex-direction: row;
		background-color: #0fa0e9;
		height: 100vh;

		.bg {
			width: 100%;
			margin-top: 250px;
		}

		.form {
			position: absolute;
			top: 75px;
			left: 0;
			z-index: 1;
			align-items: center;
			flex-direction: column;
			width: 100%;
			padding: 30px;
			box-sizing: border-box;

			.logo {
				width: 200px;
				margin: 0 auto 20px;
				display: block;
			}


			.form-box {
				margin-top: 30px;

				.uni-form-item {
					margin-bottom: 25px;
					display: flex;
					align-items: center;
					flex-direction: row;

					.icon {
						width: 25px;
						height: 25px;
						margin-right: 25px;
					}
				}
			}

			.btn-submit {
				width: 100%;
				color: #fff;
				border-color: #fff;
				border-radius: 25px;
			}

			.checkbox {
				margin-top: 15px;

				.checkbox-text {
					color: #fff;
					font-size: 16px;
				}
			}


			.btn-hover {
				background: rgba(0, 0, 0, .2);
			}
		}
	}

	.uni-input {
		color: #fff;
	}
</style>